<?php
// +----------------------------------------------------------------------
// | ebSIG
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.ebsig.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: liudaojian <liudaojian@ebsig.com>
// +----------------------------------------------------------------------

/**
 * 团购服务类
 * @package  laravel/app/Service
 * @author   liudaojian <liudaojian@ebsig.com>
 * @version 1.0
 */

namespace App\Service;

use App\Models\Tg\Tg;

use App\Models\Tg\TgBill;

use App\Models\Tg\TgAdvert;  //团购广告位表

use App\Models\Tg\TgGoods;

use App\Models\ConfigureItems;  //自定义数据项配置表

use App\Models\CheckoutConfig;

use App\Models\Goods\GoodsSale;

use App\Models\ConfigureFunction;

use App\Models\Customer\Customer;

use App\Models\Goods\GoodsMaster;

use App\Models\Goods\GoodsPicture;

use App\Models\Goods\GoodsComment;

use App\Models\Goods\GoodsSpecRelation;

use App\Models\Activity\ActivityCommonMall;

use Illuminate\Support\Facades\Redis as Redis;

class TgService
{

    /**
     * 获取会员未成团的团购订单信息
     * @param int $id 团购id
     * @param int $pcustID 会员号
     * @return array|mixed
     */
    public static function getCustomerTgOrder($id, $pcustID)
    {
        $customer_bill =  json_decode(Redis::get('G_WDH_CUSTOMER_TG_' . $id . '_' . $pcustID), true);
        if ( empty( $customer_bill ) ) {
            $customer_bill = TgBill::select('bill_no','parent_bill_no')->where([
                'bill_status' =>1,
                'pcustID' => $pcustID,
                'promotion_id' => $id
            ])
                ->paginate(1)
                ->toArray();
            if ( empty( $customer_bill['data'] ) ) {
                return [];
            } else {
                $customer_bill = [
                    'bill_no' => $customer_bill['data'][0]['bill_no'],
                    'parent_bill_no' => $customer_bill['data'][0]['parent_bill_no']
                ];
            }
        }
        return $customer_bill;
    }

    /**
     * 获取团购商品购买数量
     * @param int $id 团购id
     * @param int $goods_id 商品网购号
     * @return int
     */
    public static function getTgGoodsBuyNum($id, $goods_id)
    {
        $goods_buy_num = Redis::get('TG_GOODS_BUY_NUM_' . $id . '_' . $goods_id);
        if (empty($goods_buy_num)) {
            $tg_goods = TgGoods::select('buy_count')
                ->where([
                    'tuan_id' => $id,
                    'postID' => $goods_id
                ])
                ->first();
            if ( empty( $tg_goods ) ) {
                $goods_buy_num = 0;
            } else {
                $tg_goods = $tg_goods->toArray();
                $goods_buy_num = $tg_goods['buy_count'];
            }
        }
        return $goods_buy_num;
    }

    /**
     * 获取团购购买数量
     * @param int $id 团购id
     * @return int
     */
    public static function getTgBuyNum($id)
    {
        $buy_num = Redis::get('TG_BUY_NUM_' . $id);
        if ( empty( $buy_num )) {
            $tg = Tg::select('buy_count')->find($id);
            if ( !empty( $tg ) ) {
                $tg = $tg->toArray();
                $buy_num = $tg['buy_count'];
            } else  {
                $buy_num = 0;
            }
        }
        return $buy_num;
    }

    /**
     * 获取团购分组和广告banner
     * @return array|mixed
     */
    public static function getTgGroup () {

        $redis_key = 'WDH_API_TG_INIT';

        //读取redis缓存，key名称：WDH_API_TG_INIT，缓存时间：1个小时
        $group = Redis::get($redis_key);
        if ( !$group ) {

            $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

            $group = [
                'group' => [],
                'advert' => []
            ];

            //查询团购分组
            $group['group'] = ConfigureItems::getItems(2);

            //查询团购广告
            $advert = TgAdvert::select('photo_url' , 'link' ,'photo_type')->where(['expand_id' => 0])->get()->toArray();
            if ($advert) {
                foreach ($advert as &$ad) {
                    $group['advert'][] = [
                        'pic' => $domain_url . $ad['photo_url'],
                    ];
                }
            }

            Redis::setex($redis_key, 3600, json_encode($group, true));

        } else {
            $group = json_decode($group, true);
        }

        return $group;
    }

    /**
     * 查询团购详情缓存
     * @param int $id 团购id
     * @return null|array
     */
    public static function getCache( $id )
    {

        if ( !isset($id) || empty($id) ) {
            return [];
        }

        //从redis中获取团购缓存数据
        $tg = redisTransformation(Redis::get('G_WDH_TG_' . $id));
        if ($tg) {
            return $tg;
        }

        /**
         * =============================================
         * redis中没有团购的缓存数据
         * 1. 查询团购信息
         * 2. 查询商品详情
         * 3. 查询商品图片链接地址
         * 4. 查询商品规格
         * 5. 查询团购商品信息
         * =============================================
         */

        //查询拼团商品信息
        $tg = Tg::find($id);
        if ( empty($tg) ) {
            return [];
        }
        $tg = $tg->toArray();

        $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

        //主商品号
        $mainPostID = $tg['mainPostID'];

        //结算配置id
        $checkout_config_id = $tg['checkout_config_id'];

        //查询主商品信息
        $goods_master = GoodsMaster::find($mainPostID);
        if( !$goods_master ){
            return [];
        }

        //商品详情
        $description = $goods_master->mobile_description;
        if ( !$description ) {
            $description = $goods_master->pc_description;
        }
        $tg['goods_description'] = empty($description)? '' : htmlspecialchars_decode($description);

        //三级网购号
        $tg['postID'] = $goods_master->postID;

        //价格
        $tg['salePrice'] = $goods_master->salePrice;

        //查询商品图片链接地址
        $tg['goods_pic'] = [];
        $pic = GoodsPicture::where('mainPostID', $mainPostID)->orderBy('sortOrder', 'ASC')->get()->toArray();
        if ($pic) {
            foreach ( $pic as &$p ) {
                if( empty( $p['pictureLink'] ) ) {
                    continue;
                }
                $tg['goods_pic'][] = $domain_url . $p['pictureLink'] ;
            }
        }

        //查询商品规格
        $tg['goods_spec'] = GoodsSpecRelation::getList($mainPostID);

        //查询团购商品信息
        $tg_goods = TgGoods::where('tuan_id', $id)->get()->toArray();

        $tg['goods'] = [];
        $tg['list'] = [];
        $spec_temp = [];
        if ( $tg_goods ) {

            foreach ( $tg_goods  as &$item ) {

                //商品规格组及名称
                $item['one_level_spec_str'] = '';
                $item['two_level_spec_str'] = '';
                $item['goodsID'] = '';
                $item['goodsName'] = '';
                $item['marketPrice'] = '';
                $item['salePrice'] = '';
                $item['spec'] = '';
                $item['specID'] = '';
                $item['goodsWeight'] = '';
                $item['goodsType'] = '';
                $item['img_link'] = '';
                $item['product_code'] = '';
                $item['product_spec'] = '';

                $sale_goods_data = GoodsSale::getCache($item['postID']);
                if( !$sale_goods_data ){
                    continue;
                }

                $item['goodsID'] = $sale_goods_data['goodsID'];
                $item['goodsName'] = $sale_goods_data['goodsName'];
                $item['marketPrice'] = $sale_goods_data['marketPrice'];
                $item['salePrice'] = $sale_goods_data['salePrice'];
                $item['spec'] = $sale_goods_data['spec'];
                $item['specID'] = $sale_goods_data['specID'];
                $item['goodsWeight'] = $sale_goods_data['goodsWeight'];
                $item['goodsType'] = $sale_goods_data['goodsType'];
                $item['img_link'] = $domain_url . $sale_goods_data['goodsMainPic'];
                $item['product_code'] = $sale_goods_data['product_code'];
                $item['product_spec'] = $sale_goods_data['product_spec'];

                /**
                 * 拆分商品规格，获取对应规格及规格组信息
                 */
                if ( $sale_goods_data['specID'] ) {

                    $spec_arr = explode(',', $sale_goods_data['specID']);
                    $one_level_spec_id = isset($spec_arr[0]) && ebsig_is_int($spec_arr[0]) ? $spec_arr[0] : 0;
                    $two_level_spec_id = isset($spec_arr[1]) && ebsig_is_int($spec_arr[1]) ? $spec_arr[1] : 0;

                    if ( $one_level_spec_id > 0 ) {
                        $spec_relation = GoodsSpecRelation::where('mainPostID', $sale_goods_data['mainPostID'])->where('specID', $one_level_spec_id)->get()->toArray();
                        $item['one_level_spec_str'] = $spec_relation[0]['specGroupName'] . '：' . $spec_relation[0]['specName'];
                    }

                    if ( $two_level_spec_id > 0 ) {
                        $spec_relation = GoodsSpecRelation::where('mainPostID', $sale_goods_data['mainPostID'])->where('specID', $two_level_spec_id)->get()->toArray();
                        $item['two_level_spec_str'] = $spec_relation[0]['specGroupName'] . '：' . $spec_relation[0]['specName'];
                    }

                    if ( $one_level_spec_id > 0 ) {
                        $spec_temp[0][] = $one_level_spec_id;
                    }

                    if ( $two_level_spec_id > 0 ) {
                        $spec_temp[1][] = $two_level_spec_id;
                    }

                }

                $temp_goods_spec_id = explode(',', $sale_goods_data['specID']);
                $spec_key = '';
                foreach ($temp_goods_spec_id as &$spec_id) {
                    if (!empty($spec_id)) {
                        $spec_key .= $spec_id;
                    }
                }
                if (empty($spec_key)) {
                    $spec_key = 0;
                }

                $tg['list'][$spec_key] = [
                    'id' => $item['postID'],
                    'enable_sale_amount' => 1000,
                    'salePrice' =>$sale_goods_data['salePrice'],
                    'price' => $item['tuan_price'],
                    'img_link' => $domain_url . $sale_goods_data['goodsMainPic'],
                ];

            }

        }

        $tg['goods'] = $tg_goods;

        //除去非活动商品中的规格
        if ( $tg['goods_spec'] ) {
            foreach ( $tg['goods_spec'] as $key => &$group ) {
                if ( isset($group['list']) && isset($spec_temp[$key]) && !empty($spec_temp[$key]) ) {
                    foreach ( $group['list'] as $k => $spec ) {
                        if ( !in_array($spec['id'], $spec_temp[$key]) ) {
                            unset($group['list'][$k]);
                        }
                    }
                }
            }
        }

        //查询拼团订单配置信息
        $tg['config'] = CheckoutConfig::find($checkout_config_id)->toArray();

        $tg['activity_mall'] = [];

        //判断是否是指定门店
        if ( $tg['config'] && $tg['config']['mall_range_type'] == 2 ) {
            $search_result = ActivityCommonMall::where('activity_id', $id)->get(['mall_id'])->toArray();
            if ( $search_result ) {
                foreach ( $search_result as &$item ) {
                    $tg['activity_mall'][] = $item['mall_id'];
                }
            }
        }

        Redis::setex('G_WDH_TG_' . $id, 604800, redisTransformation($tg, 'set',604800));

        return $tg;

    }

    /**
     * 查询商品评论
     * @param $mainPostID
     * @param int $pcustID
     */
    public static function getTgGoodsComments( $mainPostID,$pcustID = 0 ) {

        if ( !ebsig_is_int( $mainPostID ) ) {
            return [];
        }

        //从redis中获取团购缓存数据
        $comment = redisTransformation(Redis::get('WDH_GOODS_COMMENTS_' . $mainPostID));

        if ( $comment ) {
            return $comment;
        }

        $where = [
            ['mainPostID',$mainPostID],
            ['commentStatus',1],
            ['display',1]
        ];

        $orWhere= [];
        if ( $pcustID > 0 ) {
            $orWhere = [
                ['pcustID',$pcustID],
                ['display',0]
            ];
        }

        $field = [
            'pcustID','createTime','commentLevel','info','answerInfo'
        ];
        $comments_data = GoodsComment::select($field)
            ->where($where)
            ->orWhere($orWhere)
            ->orderBy('commentsId', 'desc')
            ->paginate(3)
            ->toArray();

        if ( empty( $comments_data['data'] ) ) {
            return [];
        }

        $comment = [];
        foreach ( $comments_data['data'] as $item ) {

            //检查会员信息
            $customer = Customer::select('custID')->find( $item['pcustID'] );

            if ( isMobile( $customer['custID'] ) ) {
                $cust_name = hideMobile( $customer['custID'] );
            } else {
                $cust_name =  $customer['custID'];
            }

            $comment[] = [
                'cust_name' => $cust_name,
                'comment_time' => $item['createTime'],
                'comment_level' => $item['commentLevel'],
                'comment_info' => $item['info'],
                'answerInfo' => $item['answerInfo']
            ];

        }

        //查询商品所有论数
        $num = GoodsComment::getCommentCount( $mainPostID , $pcustID);

        $return_data = [
            'total' => $num['total_count'],
            'good_count' => $num['good_count'],
            'mid_count' =>  $num['mid_count'],
            'bad_count' =>  $num['bad_count'],
            'list' => $comment
        ];


        Redis::setex('WDH_GOODS_COMMENTS_' . $mainPostID, 7200, redisTransformation($return_data, 'set',7200));

        return $return_data;
    }

}